package com.gdth.bank.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.gdth.bank.BankApplication;
import com.gdth.bank.R;
import com.gdth.bank.adapter.DzCpKhETCListViewAdapter;
import com.gdth.bank.adapter.DzCpKhListViewAdapter;
import com.gdth.bank.bean.DzCpItem;
import com.gdth.bank.event.CjkhjlListEvent;
import com.gdth.bank.event.ETCMessageEvent;
import com.gdth.bank.presenter.DzCpKhXxEtcPresenter;
import com.gdth.bank.utils.ServerUtil;
import com.gdth.bank.view.DzCpKhXxEtcView;
import com.gdth.core.annotation.view.ViewInject;
import com.gdth.core.widget.BaseActivity;
import com.gdth.database.bean.DzCpkhXxDjEtc;
import com.gdth.database.bean.TAppYh;
import com.gdth.database.bean.TXtBm;
import com.gdth.widget.dialog.BaseToast;
import com.gdth.widget.dialog.DialogConfig;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase;
import com.gdth.widget.pulltorefresh.library.PullToRefreshListView;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase.Mode;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;

public class DzCpKhXxEtcListActivity extends BaseActivity implements DzCpKhXxEtcView {
	@ViewInject(id=R.id.header_label_title) TextView txt_header_title;
	@ViewInject(id=R.id.header_btn_left, click="finishClick") TextView txt_header_left;
    @ViewInject(id=R.id.header_btn_right, click="addClick") TextView txt_header_right;
    @ViewInject(id=R.id.dzcpkhxx_query, click="queryClick") TextView txt_query;
    @ViewInject(id=R.id.dzcp_editTextNote) EditText edit_query;
	@ViewInject(id=R.id.listView) PullToRefreshListView listView;
	ListView mListView;
	List<DzCpItem> listData;
	DzCpKhETCListViewAdapter mAdapter;
	List<DzCpkhXxDjEtc> dzcpkhxxetcList;
	/** 提示框 */
    ProgressDialog mProgressDialog;
    DzCpKhXxEtcPresenter  mDzCpKhXxEtcPresenter;
    private String offset="1";//上拉
    private String upset= "1";//下拉
    int tj=3;
    String  content="",time,val;
	public TAppYh user;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dzcpkhxxdjl_list);
		EventBus.getDefault().register(this);
		user = BankApplication.mInstance.getCurrentUser();
		mDzCpKhXxEtcPresenter =new DzCpKhXxEtcPresenter(this);
        initView();
	    init();
		
	}
	
	@SuppressLint("ResourceAsColor")
	private void initView() {
		txt_header_title.setText("ETC电子产品营销信息");
		 mProgressDialog = new ProgressDialog(this);
			
	        mListView = listView.getRefreshableView();
	        mListView.setDivider(new ColorDrawable(R.color.line_color));  
	        mListView.setDividerHeight(1);
	        
	        listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
				@Override
				public void onRefresh(PullToRefreshBase<ListView> refreshView) {
					String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
							DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
					
					refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
					if(refreshView.isHeaderShown()){
						  int i=Integer.parseInt(upset);
						  String time;
						  val = edit_query.getText().toString();
                    	  i = ++i;
                    	  int listDataSize=listData.size();
                    	  if(listDataSize>0){
                    	  time =listData.get(0).getDate();
                    	  }else{
                    		  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     						 time = sdf.format(new Date());
                    	  }
                    	  upset = String.valueOf(i);
                    	  JSONObject content  =new JSONObject();
                          try {
                          	content.put("upset", upset);
                          	content.put("time", time);
                          	content.put("val", val);
                  		} catch (JSONException e) {
                  			// TODO Auto-generated catch block
                  			e.printStackTrace();
                  		}
                          mDzCpKhXxEtcPresenter.getDzcpEtcUpListData(content.toString());
						Toast.makeText(getApplicationContext(), getResources().getString(R.string.param143),Toast.LENGTH_SHORT).show();
						
                      }else {
                    	  int i=Integer.parseInt(offset);
                    	  i = ++i;
                    	  int listDataSize=listData.size();
                    	  String time =listData.get(listDataSize-1).getDate();
                    	  offset = String.valueOf(i);
                    	  JSONObject content  =new JSONObject();
                          try {
                          	content.put("offset", offset);
                          	content.put("time", time);
                  		} catch (JSONException e) {
                  			// TODO Auto-generated catch block
                  			e.printStackTrace();
                  		}
                    	  mDzCpKhXxEtcPresenter.getDzcpEtcListData(content.toString());
						
							                    //上拉加载更多 业务代码
							                }
					
				}
			});

	        listView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
				@Override
				public void onLastItemVisible() {
					
				}
			});
	        
	        listData = new ArrayList<DzCpItem>();
	        
	        
	        mAdapter = new DzCpKhETCListViewAdapter(this, listData);

	        listView.setAdapter(mAdapter);
	        
	        listView.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
				   DzCpItem item=listData.get(position-1);
				   String appuuid=	item.getKey();
				   String zt=item.getZt();
					   Intent intent=new Intent();
					   intent.setClass(DzCpKhXxEtcListActivity.this, DzCpKhXxEtcWcjXxActivity.class);
					   intent.putExtra("appuuid", appuuid);
					   intent.putExtra("zt", zt);
					   intent.putExtra("sczt", "未成交");
					   /*startActivity(intent);*/
					   startActivityForResult(intent,0);
				}});
	        
	         listView.setMode(Mode.BOTH);
	        
	        
	        registerForContextMenu(mListView);
	}
	private void init() {
		listData.clear();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        String time = formatter.format(new  Date());
        JSONObject content  =new JSONObject();
        try {
        	content.put("offset", offset);
        	content.put("time", time);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mDzCpKhXxEtcPresenter.getDzcpEtcListData(content.toString());
		
		
	}
	@Override
	public void showProgressDialog(String msg) {
		// TODO Auto-generated method stub
		mProgressDialog.setMessage(msg);
		mProgressDialog.show();
	}

	@Override
	public void hideProgressDialog() {
		// TODO Auto-generated method stub
		mProgressDialog.hide();
	}

	@Override
	public void showMessage(String msg) {
		// TODO Auto-generated method stub
		BaseToast.getInstance().ShowSystemToast(this, msg);
	}

	@Override
	public void updateView(int type, Object Obj) {
		// TODO Auto-generated method stub
		if (type == ServerUtil.server_save){
			showMessage(getResources().getString(R.string.param144));
		} else if (type == ServerUtil.server_delete){
			showMessage(getResources().getString(R.string.param145));
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void updateList(List<DzCpkhXxDjEtc> mList) {
		// TODO Auto-generated method stub
	/*	dzcpkhxxetcList = mList;
		for (DzCpkhXxDjEtc mdzcpkhxxlList : mList){
			DzCpItem mImageItem = new DzCpItem();
	        mImageItem.setKey(mdzcpkhxxlList.getAppUuid());
	        mImageItem.setValue(mdzcpkhxxlList.getKhMc());
	        mImageItem.setSfz(mdzcpkhxxlList.getKhZjh());
	        mImageItem.setType(0);
	        int xgzt=mdzcpkhxxlList.getXgzt();
	        if(xgzt==0){
	        	 mImageItem.setZt("未上传");
	        }
	        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
	        String dateString = formatter.format(mdzcpkhxxlList.getSqSj());
	        mImageItem.setDate(dateString);
	        listData.add(mImageItem);
		}
		listView.onRefreshComplete();
		mAdapter.notifyDataSetChanged();
		showMessage("刷新成功");*/
		}

	@Override
	public void updateListUp(List<DzCpkhXxDjEtc> mList) {
		// TODO Auto-generated method stub
		dzcpkhxxetcList = mList;
		for (DzCpkhXxDjEtc mdzcpkhxxlList : mList){
			DzCpItem mImageItem = new DzCpItem();
	        mImageItem.setKey(mdzcpkhxxlList.getAppUuid());
	        mImageItem.setValue(mdzcpkhxxlList.getKhMc());
	        mImageItem.setSfz(mdzcpkhxxlList.getKhZjh());
	        mImageItem.setType(0);
	        int sbzt=mdzcpkhxxlList.getSbZt();
	        if(sbzt==0){
	        	 mImageItem.setZt("未成交");
	        }
	        else if(sbzt ==1){
	        	mImageItem.setZt("已成交");
	        }
	        mImageItem.setLx("ETC");
	        mImageItem.setImg("ETC");
	        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
	        String dateString = formatter.format(mdzcpkhxxlList.getSqSj());
	        mImageItem.setDate(dateString);
	        String [] str = dateString.split(" "); 
	        mImageItem.setXsSj(str[0]);
	        listData.add(mImageItem);
		}
		 Collections.sort(listData, new Comparator<DzCpItem>() {
			   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			   private Date getDate(DzCpItem m) {
		           if (m == null || m.getDate() == null)
		               return null;
		           try {
		               return sdf.parse(m.getDate());
		           } catch (ParseException e) {
		               return null;
		           }
		       }
					@Override
					public int compare(DzCpItem lhs, DzCpItem rhs) {
						// TODO Auto-generated method stub
						Date d1 = getDate(lhs);
		                Date d2 = getDate(rhs);
		                if (d1 == null && d2 == null)
		                    return 0;
		 
		                if (d1 == null)
		                    return -1;
		                if (d2 == null)
		                    return 1;
		                return d2.compareTo(d1);
					}
		        });
				
		  
		listView.onRefreshComplete();
		mAdapter.notifyDataSetChanged();
		showMessage("刷新成功");
		
	}
	public void queryClick(View arg0){
		query();
	}
	
	private void query(){
		listData.clear();
	    val = edit_query.getText().toString();
		mDzCpKhXxEtcPresenter.getBdserach(val);
		
		
	}

	@Override
	public void success() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void updateListBm(List<TXtBm> mList) {
		// TODO Auto-generated method stub
		
	}
	@Override  
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
		  case RESULT_OK:
			  mAdapter.notifyDataSetChanged();
		  default:
		   break;
		  }
		
	}

	@Override
	public void scsuccess() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void AlertDialog() {
		// TODO Auto-generated method stub
		
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void getDataclick(ETCMessageEvent Event) {
		//query(1);
		switch (Event.getType()){
			case ETCMessageEvent.ETCLIST_DEL_CODE: //  时间: 2020/4/21 9:46 AM ,作者: xjc, 作用: 拜访删除
				DialogConfig config = new DialogConfig(this, "是否确定删除该条ETC申报", true, new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						mDzCpKhXxEtcPresenter.getDzcpEtcDelData(user.getSfz(),Event.getUuid());
					}
				});
				config.show();

				break;
			case ETCMessageEvent.ETCLIST_DEL_SUCCESS:
				if(Event.getUuid().equals("1")){
					init();
				}else{
					BaseToast.getInstance().ShowCenterToast(DzCpKhXxEtcListActivity.this,"没有删除权限");
				}
				break;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}
}
